//
//  OptionsView.swift
//  IDF
//
//  Created by 陈徐挺 on 29/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import Reusable
import Dollar

class OptionsView: UIView,  NibOwnerLoadable{

    @IBOutlet weak var bgViewHeight: NSLayoutConstraint!
    @IBOutlet weak var bgView: UIView!
    var clickCallback : ((_ selection : Selection) -> Void)!
    var oheight: CGFloat = 0
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadNibContent()
    }

    
    func setWithOptions(_ options: [Selection]) {
        oheight = CGFloat(options.count) * (10 + 50) + 20 + 20 - 10
        Dollar.each(options) { (index, item) in
            let y = ( 10 + 50 ) * index + 20
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: 20, y: y, width: Int(kWidth - 20 - 20), height: 50)
            btn.setTitle("    \(item.selectText!)", for: .normal)
            btn.setTitleColor( UIColor(hexString: "333333") , for: .normal)
            btn.backgroundColor = UIColor(hexString: "f8faff")
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor(hexString: "e9f0ff")?.cgColor
            btn.layer.cornerRadius = 2
            btn.contentHorizontalAlignment = .left
            btn.setBlockFor(.touchUpInside, block: {[weak self] (btn) in
                self?.hide()
                if let cb = self?.clickCallback  {
                    cb(item)
                }
            })
            bgView.addSubview(btn)
        }
    }
    
    func show(){
        
        UIView.animate(withDuration: 0.3) {
            self.bgViewHeight.constant = self.oheight
            self.layoutIfNeeded()
        }
    }
    
    
    func hide() {
        UIView.animate(withDuration: 0.3, animations: {
            self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.01)
            self.bgViewHeight.constant = 0
            self.layoutIfNeeded()
        }) { (finish) in
            if(finish){
                self.removeFromSuperview()
            }
        }
    }
    
    @IBAction func hideBtn(_ sender: Any) {
        hide()
    }
}
